﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Telerik.Windows.Controls;
using WCFDynamicProxyLibrary.DynamicProxy;
using Broker.Model;
using NHibernate;
using BrokerBase.Lib.Client;
using Broker.Comm;
using System.Text.RegularExpressions;
using Broker.Update;
using System.ComponentModel;
using Microsoft.Win32;
using System.IO;
using System.ServiceModel.Description;
using System.ServiceModel;
using Broker.DataService;


namespace Broker
{
    /// <summary>
    /// Interaction logic for InvitedForm.xaml
    /// </summary>
    public partial class InvitedForm
    {
        //private string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        private BackgroundWorker work=new BackgroundWorker();
        private bool isSave;
        private bool isGetCode;

        private RegistrantInfo regInfo;
        private TerminalInfo terminalInfo;
        private ResultInvitedCodeInfo result;

        private const int MAX_LENGTH = 256 * 1024 * 1024;//256M的最大数据

        public InvitedForm()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(InvitedForm_Loaded);
            PreviewClosed += new EventHandler<WindowPreviewClosedEventArgs>(InvitedForm_PreviewClosed);
        }

        void InvitedForm_Loaded(object sender, RoutedEventArgs e)
        {
            txtInviteQty.Text = "还剩：" +  AppGlobal.ResultClientRegInfo.InviteQty + " 个邀请码";

            work.DoWork += new DoWorkEventHandler(work_DoWork);
            work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerCompleted);

            
        }

        void InvitedForm_PreviewClosed(object sender, WindowPreviewClosedEventArgs e)
        {
            if (work.IsBusy)
            {
                MessageBox.Show("正在获取注册码,请稍等...");
                e.Cancel = true;
            }

            if (isGetCode && !isSave)
            {
                MessageBox.Show("请保存邀请码后再退出!","提示");
                e.Cancel = true;
            }
        }

        private void btnInvite_Click(object sender, RoutedEventArgs e)
        {

            if (!work.IsBusy)
            {
                if (MessageBox.Show("是否要获取一个邀请码?", "提示", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                    return;

                if (AppGlobal.ResultClientRegInfo.InviteQty <= 0)
                {
                    MessageBox.Show("没有可用的邀请码");
                    return;
                }
                busyRoot.IsIndeterminate = true;
                busyRoot.IsBusy = true;

                this.IsEnabled = false;

                txtCodeDescription.Text = "正在连接服务器,请等待...";

                try
                {
                    regInfo = LicenseInfo.GetInstance().CreateRegistrantInfo();
                    terminalInfo = ClientUtil.CreateTerminalInfo();

                    //regInfo = new RegistrantInfo();
                    //regInfo.UserName = "宫二";
                    //regInfo.PresenterName = "李2";
                    //regInfo.LicenseCode = "";

                    //terminalInfo = new TerminalInfo();
                    //terminalInfo.DISKSerialNo = "56393059444a3652202020202020202020202020";
                    //terminalInfo.MACSerialNo = "00:24:81:F1:6D:0D";
                    //terminalInfo.MBSerialNo = "CNG92708N9";
                    //terminalInfo.ClientTime = DateTime.Parse("2013-01-21");
                    //terminalInfo.OSVersion = "Microsoft Windows NT 5.1.2600 Service Pack 3";

                    //StringBuilder sb = new StringBuilder();
                    //sb.Append(regInfo.GetXml());
                    //sb.Append(Environment.NewLine);
                    //sb.Append(terminalInfo.GetXml());

                    //AppGlobal.Log.Error(sb.ToString(), new Exception());

                    work.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + ex.StackTrace);
                }
                finally
                {
                    busyRoot.IsBusy = false;
                    this.IsEnabled = true;
                }
            }
        }

        void work_DoWork(object sender, DoWorkEventArgs e)
        {
            ChannelFactory<IDataService> factory = AppGlobal.CreateDataServiceFactory();

            try
            {
                factory.Open();
                IDataService svr = factory.CreateChannel();

                this.Dispatcher.Invoke(new Action(() =>
                    {
                        txtCodeDescription.Text += Environment.NewLine;
                        txtCodeDescription.Text += "正在获取邀请码，请等待...";
                    }));
                string text=svr.GetInviteCode(regInfo.GetData(), terminalInfo.GetData());

                result = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultInvitedCodeInfo>(text);

                factory.Close();
            }
            catch (Exception er)
            {
                factory.Abort();
                this.Dispatcher.Invoke(new Action(() =>
                {
                    txtCodeDescription.Text += Environment.NewLine;
                    txtCodeDescription.Text += er.Message;
                }));
            }
        }

        void work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (result != null)
            {
                if (result.IsSuccess)
                {
                    StringBuilder sb = new StringBuilder();

                    sb.Append(Environment.NewLine);
                    sb.Append("邀请码:  ");
                    sb.Append(result.Code);
                    sb.Append(Environment.NewLine);
                    sb.Append("有效期： " + result.Period + " 个月");
                    sb.Append(Environment.NewLine);
                    sb.Append("请在:" + result.RegPeriod + " 天内注册，否则失效!");
                    sb.Append(Environment.NewLine);
                    sb.Append("请把上述信息通过邮件或短信发送给你的朋友");

                    txtCodeDescription.Text = sb.ToString();
                    txtInviteQty.Text = "还剩：" + result.Qty + " 个邀请码";
                    isGetCode = true;
                }
                else
                {
                    txtCodeDescription.Text += "获取邀请码失败!";
                    txtCodeDescription.Text += Environment.NewLine;
                    txtCodeDescription.Text += result.Description;
                }
                
                btnInvite.IsEnabled = false;
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.DefaultExt = "*.txt";
            dlg.Filter = @"文本文件(*.txt)|*.txt";

            if (dlg.ShowDialog() == true)
            {
                string path = dlg.FileName;

                StreamWriter sw = new StreamWriter(path);

                sw.Write(txtCodeDescription.Text);

                sw.Close();

                isSave = true;
            }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

    }
}
